package com.example.administrator.printoutindemo;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.administrator.printoutindemo.services.dyjApplication;
import com.example.administrator.printoutindemo.view.MyImageButton;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;


public class GPSMainActivity extends Activity {

	ProgressDialog progressDiaog;

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";
	private static final int BINDDATA = 0;// 停止执行
	private static final int TOAST_NOMSG = 1;// 文本框没有输入信息提示
	private static final int NETERROR = 2;// 网络不正常

	private PowerManager powerManager = null;
	private WakeLock wakeLock = null;

	private GPSLocation gpsLocation = new GPSLocation();
	private GpsInfo gpsInfo = null;

	private EditText s_gps_proid;
	private EditText s_gps_purchaseid;
	private EditText s_gps_mid;
	private TextView s_gps_mjd;
	private TextView s_gps_mwd;
	private TextView s_gps_num;
	private TextView s_gps_reload;

	private MyImageButton s_gps_btn_start;
	private MyImageButton s_gps_btn_end;
	private MyImageButton s_gps_btn_QRCode;

	public LocationManager lm;
	private static final String TAG = "GPS Services";

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_gps_activity_main);

		this.setTitle("GPS定位");

		s_gps_mid = (EditText) findViewById(R.id.s_gps_mid);
		s_gps_proid = (EditText) findViewById(R.id.s_gps_proid);
		s_gps_purchaseid = (EditText) findViewById(R.id.s_gps_purchaseid);
		s_gps_mjd = (TextView) findViewById(R.id.s_gps_mjd);
		s_gps_mwd = (TextView) findViewById(R.id.s_gps_mwd);
		s_gps_num = (TextView) findViewById(R.id.s_gps_num);
		s_gps_reload = (TextView) findViewById(R.id.s_gps_reload);

		gpsInfo = new GpsInfo();

		// 让屏幕常亮
		powerManager = (PowerManager) this.getSystemService(this.POWER_SERVICE);
		wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
				"My Lock");

		s_gps_btn_start = (MyImageButton) findViewById(R.id.s_gps_btn_start);
		s_gps_btn_end = (MyImageButton) findViewById(R.id.s_gps_btn_end);
		s_gps_btn_QRCode = (MyImageButton) findViewById(R.id.s_gps_btn_QRCode);

		s_gps_btn_start.setOnClickListener(new s_gps_btn_start_Click());
		s_gps_btn_end.setOnClickListener(new s_gps_btn_end_Click());
		s_gps_btn_QRCode.setOnClickListener(new s_gps_btn_QRCode_Click());

		registerGPS();// 在这里获取gps信息，更新到textview里

	}

	// 开始定位
	private class s_gps_btn_start_Click implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			if (s_gps_mid.getText().toString().equals("")
					&& s_gps_proid.getText().toString().equals("")
					&& s_gps_purchaseid.getText().toString().equals("")) {

				Toast.makeText(GPSMainActivity.this, "采购订单号、项目编号、物料编码请至少填写一处！", Toast.LENGTH_SHORT).show();

			} else {
				hanlder.post(task);
			}


		}
	}

	// 结束定位
	private class s_gps_btn_end_Click implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					uploadGpsInfo(1);
				}
			}).start();

			hanlder.removeCallbacks(task);

			Intent listIntent1 = new Intent();
			listIntent1.setClass(GPSMainActivity.this, LoginGPSActivity.class);
			startActivity(listIntent1);

		}
	}

	// 扫码
	private class s_gps_btn_QRCode_Click implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			Intent openCameraIntent = new Intent(GPSMainActivity.this,
					CaptureActivity.class);
			startActivityForResult(openCameraIntent, 0);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			String scanResult = bundle.getString("result");
			s_gps_mid.setText(scanResult);
		}
	}

	private final Handler hanlder = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case GPSMainActivity.BINDDATA:

					SimpleDateFormat formatter = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss ");
					Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
					String time = formatter.format(curDate);
					s_gps_reload.setText(time);

					break;

				case GPSMainActivity.TOAST_NOMSG:
					Toast.makeText(GPSMainActivity.this,  "请输入发送内容!",
							Toast.LENGTH_LONG).show();

					progressDiaog.dismiss();// 将进度条消除
					break;

				case GPSMainActivity.NETERROR:
					Toast.makeText(GPSMainActivity.this, "网络连接错误,请检查网络！",
							Toast.LENGTH_LONG).show();

					progressDiaog.dismiss();// 将进度条消除
					break;
			}
			super.handleMessage(msg);
		}
	};

	private final Runnable task = new Runnable() {

		@Override
		public void run() {
			try {

				ConnectivityManager manager = (ConnectivityManager) GPSMainActivity.this
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo moblie = manager
						.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				NetworkInfo wifi = manager
						.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

				if (!moblie.isConnected() && !wifi.isConnected()) {
					hanlder.removeCallbacks(task);// 停止
					Message m = new Message();
					m.what = GPSMainActivity.NETERROR;
					GPSMainActivity.this.hanlder.sendMessage(m);
					hanlder.postDelayed(this, 15000);//15秒后重连

				} else if (wifi.isConnected()) {
					hanlder.postDelayed(this, 15000);// 如果在wifi条件下，15秒刷新一次


					new Thread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							uploadGpsInfo(0);
						}
					}).start();

					Message m = new Message();
					m.what = GPSMainActivity.BINDDATA;
					GPSMainActivity.this.hanlder.sendMessage(m);
				} else if (moblie.isConnected()) {
					hanlder.postDelayed(this, 15000);// 如果在移动网络下，15秒刷新一次

					new Thread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							uploadGpsInfo(0);
						}
					}).start();

					Message m = new Message();
					m.what = GPSMainActivity.BINDDATA;
					GPSMainActivity.this.hanlder.sendMessage(m);
				} else {
					hanlder.postDelayed(this, 15000);//15秒后重连
				}

			} catch (Exception e) {
				e.printStackTrace();
				hanlder.removeCallbacks(task);// 停止
				hanlder.postDelayed(this, 15000);//15秒后重连
			}

		}
	};

	// 上传数据至服务器
	private boolean uploadGpsInfo(int iscover) {

		GpsInfo n = new GpsInfo();

		n.setMjd(s_gps_mjd.getText().toString());
		n.setMwd(s_gps_mwd.getText().toString());
		n.setProid(s_gps_proid.getText().toString());
		n.setPurchaseid(s_gps_purchaseid.getText().toString());
		n.setMid(s_gps_mid.getText().toString());
		n.setIsover(iscover);
		n.setGdatetime(s_gps_reload.getText().toString());
		n.setSubmitUid(((dyjApplication) getApplication()).get_user_id());

		boolean bl = false;

		String jsonStr = gpsInfo.ConvertToJson(n);

		try {

			/****************** ����webService ***********************/
			// ����.net ��WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "InsertGPSInfo";

			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";// "http://192.168.1.101/webservice/default.asmx";
			// // 10.0.2.2
			// ΪAndroidģ�����ı���(localhost)IP
			String soapAction = nameSpace + methodName;

			// �������Ӳ���
			SoapObject request = new SoapObject(nameSpace, methodName);

			// �������Բ����� ����صĺ����������뵽�����С�
			request.addProperty("modelJson", jsonStr);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soapЭ��汾������SoapEnvelope.VER11��Soap
			// V1.1��;

			// ע�⣺��������Ƕ�dotnetwebserviceЭ���֧��,���dotnet��webservice
			// ��ָ��rpc��ʽ����true����Ҫ��false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//�����������
			envelope.bodyOut = request; // enveloper.bodyOut=request ��
			// envelope.setOutputSoapObject(request)
			// Ч����ͬ��
			// step4 ����HttpTransportSE����
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 ����WebService
			ht.call(soapAction, envelope); // �ؼ���һ�����ܶ����ⶼ����һ������ʱ�������⡣Ҫô��IIS�����⣬Ҫô��ksoap2��ز���û���úá�
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				if (!("0".equals(response.toString()))) {
					int gid = Integer.parseInt(response.toString());

				}
				bl = true;
			}
			/****************** ����webService���� ***********************/

		} catch (Exception e) {
			e.printStackTrace();
		}

		return bl;
	}

	private void registerGPS() {
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// �ж�GPS�Ƿ���������
		if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
			// ���ؿ���GPS�������ý���
			// Intent intent = new
			// Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			// startActivityForResult(intent, 0);
			return;
		}

		// Ϊ��ȡ����λ����Ϣʱ���ò�ѯ����
		String bestProvider = lm.getBestProvider(getCriteria(), true);
		// ��ȡλ����Ϣ
		// ��������ò�ѯҪ��getLastKnownLocation�������˵Ĳ���ΪLocationManager.GPS_PROVIDER
		if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			// TODO: Consider calling
			//    Activity#requestPermissions
			// here to request the missing permissions, and then overriding
			//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
			//                                          int[] grantResults)
			// to handle the case where the user grants the permission. See the documentation
			// for Activity#requestPermissions for more details.
			return;
		}
		Location location = lm.getLastKnownLocation(bestProvider);
		// Location location=
		// lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		updateView(location);
		// ����״̬
		lm.addGpsStatusListener(listener);
		// �󶨼�������4������
		// ����1���豸����GPS_PROVIDER��NETWORK_PROVIDER����
		// ����2��λ����Ϣ�������ڣ���λ����
		// ����3��λ�ñ仯��С���룺��λ�þ���仯������ֵʱ��������λ����Ϣ
		// ����4������
		// ��ע������2��3���������3��Ϊ0�����Բ���3Ϊ׼������3Ϊ0����ͨ��ʱ������ʱ���£�����Ϊ0������ʱˢ��

		// 1�����һ�Σ�����Сλ�Ʊ仯����1�׸���һ�Σ�
		// ע�⣺�˴�����׼ȷ�ȷǳ��ͣ��Ƽ���service��������һ��Thread����run��sleep(10000);Ȼ��ִ��handler.sendMessage(),����λ��
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
				locationListener);
		// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1,
		// locationListener);
	}

	// λ�ü���
	private LocationListener locationListener = new LocationListener() {

		/**
		 * λ����Ϣ�仯ʱ����
		 */
		public void onLocationChanged(Location location) {
			updateView(location);
			Log.i(TAG, "时间：" + location.getTime());
			Log.i(TAG, "经度：" + location.getLongitude());
			Log.i(TAG, "纬度：" + location.getLatitude());
			Log.i(TAG, "海拔：" + location.getAltitude());
		}

		/**
		 * GPS״̬�仯ʱ����
		 */
		public void onStatusChanged(String provider, int status, Bundle extras) {
			switch (status) {
				// GPS״̬Ϊ�ɼ�ʱ
				case LocationProvider.AVAILABLE:
//					Log.i(TAG, "当前GPS状态为可见状态");
					break;
				// GPS״̬Ϊ��������ʱ
				case LocationProvider.OUT_OF_SERVICE:
//					Log.i(TAG, "当前GPS状态为服务区外状态");
					break;
				// GPS״̬Ϊ��ͣ����ʱ
				case LocationProvider.TEMPORARILY_UNAVAILABLE:
//					Log.i(TAG, "当前GPS状态为暂停服务状态");
					break;
			}
		}

		/**
		 * GPS����ʱ����
		 */
		public void onProviderEnabled(String provider) {
			if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
				// TODO: Consider calling
				//    Activity#requestPermissions
				// here to request the missing permissions, and then overriding
				//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
				//                                          int[] grantResults)
				// to handle the case where the user grants the permission. See the documentation
				// for Activity#requestPermissions for more details.
				return;
			}
			Location location = lm.getLastKnownLocation(provider);
			updateView(location);
		}

		/**
		 * GPS����ʱ����
		 */
		public void onProviderDisabled(String provider) {
			updateView(null);
		}
	};

	// ״̬����
	GpsStatus.Listener listener = new GpsStatus.Listener() {
		public void onGpsStatusChanged(int event) {
			switch (event) {
				// ��һ�ζ�λ
				case GpsStatus.GPS_EVENT_FIRST_FIX:
					Log.i(TAG, "��һ�ζ�λ");
					break;
				// ����״̬�ı�
				case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
					Log.i(TAG, "����״̬�ı�");
					// ��ȡ��ǰ״̬
					if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
						// TODO: Consider calling
						//    Activity#requestPermissions
						// here to request the missing permissions, and then overriding
						//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
						//                                          int[] grantResults)
						// to handle the case where the user grants the permission. See the documentation
						// for Activity#requestPermissions for more details.
						return;
					}
					GpsStatus gpsStatus = lm.getGpsStatus(null);
				// ��ȡ���ǿ�����Ĭ�����ֵ
				int maxSatellites = gpsStatus.getMaxSatellites();
				// ����һ��������������������
				Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
						.iterator();
				int count = 0;
				while (iters.hasNext() && count <= maxSatellites) {
					GpsSatellite s = iters.next();
					count++;
				}
				// System.out.println("��������" + count + "������");
				s_gps_num.setText("搜索到" + count + "颗卫星");
				break;
			// ��λ����
			case GpsStatus.GPS_EVENT_STARTED:
				Log.i(TAG, "��λ����");
				break;
			// ��λ����
			case GpsStatus.GPS_EVENT_STOPPED:
				Log.i(TAG, "��λ����");
				break;
			}
		};
	};

	/**
	 * ʵʱ�����ı�����
	 *
	 * @param location
	 */
	private void updateView(Location location) {

		if (location != null) {
			s_gps_mjd.setText(String.valueOf(location.getLongitude()));
			s_gps_mwd.setText(String.valueOf(location.getLatitude()));
			gpsLocation.setLongitude(String.valueOf(location.getLongitude()));// ����
			gpsLocation.setLatitude(String.valueOf(location.getLatitude()));// ά��
		} else {
			s_gps_mjd.setText("-");
			s_gps_mwd.setText("-");
		}

	}

	/**
	 * ���ز�ѯ����
	 *
	 * @return
	 */
	private Criteria getCriteria() {
		Criteria criteria = new Criteria();
		// ���ö�λ��ȷ�� Criteria.ACCURACY_COARSE�Ƚϴ��ԣ�Criteria.ACCURACY_FINE��ȽϾ�ϸ
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		// �����Ƿ�Ҫ���ٶ�
		criteria.setSpeedRequired(false);
		// �����Ƿ�������Ӫ���շ�
		criteria.setCostAllowed(false);
		// �����Ƿ���Ҫ��λ��Ϣ
		criteria.setBearingRequired(false);
		// �����Ƿ���Ҫ������Ϣ
		criteria.setAltitudeRequired(false);
		// ���öԵ�Դ������
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		return criteria;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		hanlder.removeCallbacks(task);
	}

	@Override
	protected void onResume() {
		super.onResume();
		wakeLock.acquire();
	}

	@Override
	protected void onPause() {
		super.onPause();
		wakeLock.release();
	}
}
